package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.ProListMapper;
import com.indusfo.spc.mapper.ProMapper;
import com.indusfo.spc.mapper.StationMapper;
import com.indusfo.spc.mapper.UploadMapper;
import com.indusfo.spc.pojo.Datadict;
import com.indusfo.spc.pojo.Pro;
import com.indusfo.spc.pojo.ProList;
import com.indusfo.spc.service.ProService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 工序业务层
 *
 * @author xuz
 * @date 2018/11/23 2:30 PM
 */
@Service
public class ProServiceImpl implements ProService {

    private  static  final Logger logger = LoggerFactory.getLogger(ProServiceImpl.class);

    @Resource
    private ProMapper proMapper;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private ProListMapper proListMapper;


    @Resource
    private UploadMapper uploadMapper;
    /**
     * 工序更新
     *
     * @author xuz
     * @date 2018/11/23 1:54 PM
     * @param pro
     * @return com.indusfo.spc.vo.JSONObject
     */
    /*@Override
    public JSONObject updatePro(Pro pro, Integer[] staIds, HttpServletRequest request) {
        String vcRemark = "";
        if(pro.getVcRemark() == null) {
            pro.setVcRemark(vcRemark);
        }
        try {
            //更新id不能为空
            if(pro.getlProId() == null) {
                throw new ParamsErrorException("请选择要更新的工序");
            }
            if(pro.getlDataState()==null){
                pro.setlDataState(1);
            }
            // 如果参数不合法，抛出参数异常
            checkParam(pro);

            // 调用存储过程
            int row = proMapper.updateByPrimaryKeySelective(pro);// 返回影响行数
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败！");
            }
            *//*if(staIds!=null){
                System.out.println(pro.getlProId());
                int flag = proListMapper.insertProList(pro.getlProId(),staIds,1);
                if(flag == 0) {
                    throw new ModifyFailedException("新增工位失败！");
                }
            }*//*
           //获取到session当中的数据
            HttpSession session = request.getSession();
            List<Integer> staIds1 = (List<Integer>)session.getAttribute("staIds");
            if(staIds1!=null){
                    if(!staIds1.isEmpty()){
                        System.out.println(pro.getlProId());
                        Integer[] newArray=new Integer[staIds1.size()];
                        for (int i = 0; i < staIds1.size(); i++) {
                            newArray[i]=staIds1.get(i);
                        }
                        int flag = proListMapper.insertProList(pro.getlProId(),newArray,1);
                        if(flag == 0) {
                            throw new ModifyFailedException("新增工位失败！");
                        }
                    }
                    session.removeAttribute("staIds");
                    //session.invalidate();
            }

            return JSONObject.oK("更新成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }*/
    @Override
    public JSONObject updatePro(Pro pro, Integer[] staIds, HttpServletRequest request) {
        String vcRemark = "";
        if(pro.getVcRemark() == null) {
            pro.setVcRemark(vcRemark);
        }
        try {
            //更新id不能为空
            if(pro.getlProId() == null) {
                throw new ParamsErrorException("请选择要更新的工序");
            }
            if(pro.getlDataState()==null){
                pro.setlDataState(1);
            }
            // 如果参数不合法，抛出参数异常
            checkParam(pro);
            // 调用存储过程
            int row = proMapper.updateByPrimaryKeySelective(pro);// 返回影响行数
            if(row == 0) {
                throw new ModifyFailedException("数据新增失败！");
            }
            //删除工位
                //通过工序ID获取所有的工位进行过滤
                List<ProList> proLists = proListMapper.queryByProId(pro.getlProId());
                //传递数组数组转集合
                List<Integer> array2List=new ArrayList<>();
                //数据库中删除的工位集合
                List<Integer> dataBaseList=new ArrayList<>();
                //判断当前数组是否还存之前数据库中加载过的工位信息
                if(staIds!=null && staIds.length>0){
                    for (int i = 0; i < staIds.length; i++) {
                        array2List.add(staIds[i]);
                    }
                }else if(proLists!=null && proLists.size()>0){
                    for (ProList proList : proLists) {
                        //如果走到这里说明传递的工位数组为空说明当前列表当中已经把原先数据库存的工位都删除掉了
                            dataBaseList.add(proList.getStaId());
                    }
                }
                //如果两者都不为空
                if(proLists!=null && array2List!=null && proLists.size()>0 && array2List.size()>0){
                    for (ProList proList : proLists) {
                        //如果不包含了,说明需要删除
                        if(!array2List.contains(proList.getStaId())){
                            dataBaseList.add(proList.getStaId());
                        }
                    }
                }
                //删除工位操作
                if(dataBaseList!=null && dataBaseList.size()>0){
                    Integer[] dataBaseArray=new Integer[dataBaseList.size()];
                    for (int i = 0; i < dataBaseList.size(); i++) {
                        dataBaseArray[i]=dataBaseList.get(i);
                    }
                    int i = proListMapper.deleteProList(pro.getlProId(), dataBaseArray, 2);
                }
            //删除工位

            //新增工位
            if(staIds !=null && staIds.length>0){


                //旧的工位集合
                List<Integer> oldstaIdsJiHe=new ArrayList<>();
                //工位集合
                List<Integer> staIdsJiHe=new ArrayList<>();

                //将数据库中已经存在的工位与所传的工位数组进行比较判断是否包含,不包含则进行新增
                if(proLists!=null && proLists.size()>0){

                    //将已经添加到数据库中的工位赋值给一个集合来进行判断
                    for(int i = 0; i < proLists.size(); i++){
                        oldstaIdsJiHe.add(proLists.get(i).getStaId());
                    }
                    //旧工位集合不为空
                    if(oldstaIdsJiHe!=null && oldstaIdsJiHe.size()>0){
                        for (int i = 0; i < staIds.length; i++) {
                            if(!oldstaIdsJiHe.contains(staIds[i])){
                                staIdsJiHe.add(staIds[i]);
                            }
                        }
                    }else {
                        //说明该工序下没有存工位
                        for (int i = 0; i < staIds.length; i++) {
                                staIdsJiHe.add(staIds[i]);
                        }
                    }

                }else{
                    //说明该工序下没有存工位
                        for (int i = 0; i < staIds.length; i++) {
                            staIdsJiHe.add(staIds[i]);
                        }
                }
                if(staIdsJiHe!=null && staIdsJiHe.size()>0){
                    Integer[] newStaIdsArray=new Integer[staIdsJiHe.size()];
                    for (int i = 0; i < newStaIdsArray.length; i++) {
                        newStaIdsArray[i]=staIdsJiHe.get(i);
                    }

                    int i = proListMapper.insertProList(pro.getlProId(), newStaIdsArray, 1);
                    if(i==0){
                        throw new ModifyFailedException("工位新增失败！");
                    }
                }
            }


            return JSONObject.oK("更新成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 工序新增
     *
     * @author xuz
     * @date 2018/11/23 1:54 PM
     * @param pro
     * @return com.indusfo.spc.vo.JSONObject
     */
   /* @Transactional
    @Override
    public JSONObject insertPro(Pro pro,Integer[] staIds, HttpServletRequest request) {
        String vcRemark = "";
        if(pro.getVcRemark() == null) {
            pro.setVcRemark(vcRemark);
        }
        try {
            //新增时不能有工序id
            if(pro.getlProId() != null) {
                throw new ParamsErrorException("新增工序，不能有工序id");
            }
            if(pro.getlDataState()==null){
                pro.setlDataState(1);
            }
            // 如果参数不合法，抛出参数异常
            checkParam(pro);

            // 调用存储过程
            int row = proMapper.insertSelective(pro);
            if(row == 0) {
                throw new ModifyFailedException("新增工序失败！");
            }
            *//**
             * @author: louk
             * @Description: :在添加成功之后对工位进行新增
             * @date: 2019/9/5 14:03
             *//*
           *//* if(staIds!=null){
                List<Pro> pros = proMapper.listPros(pro);
                if(!pros.isEmpty()){
                    int flag = proListMapper.insertProList(pros.get(0).getlProId(),staIds,1);
                    if(flag == 0) {
                        throw new ModifyFailedException("新增工位失败！");
                    }
                }
            }*//*
            *//**
             * @author: louk
             * @Description:对session当中所存储的数据进行新增
             * @date: 2019/9/11 19:36
             *
             *//*
            //获取到session当中的数据
            HttpSession session = request.getSession();
            List<Integer> staIds1 = (List<Integer>)session.getAttribute("staIds");
            //当session当中的不为空时 进行新增
            if(staIds1!=null){
                if(!staIds1.isEmpty()){
                List<Pro> pros = proMapper.listPros(pro);
                if(!pros.isEmpty()){
                    Integer[] newArray=new Integer[staIds1.size()];
                    for (int i = 0; i < staIds1.size(); i++) {
                        newArray[i]=staIds1.get(i);
                    }
                    int flag = proListMapper.insertProList(pros.get(0).getlProId(),newArray,1);
                    if(flag == 0) {
                        throw new ModifyFailedException("新增工位失败！");
                    }
                }
                }
                session.removeAttribute("staIds");
            }

            //session.invalidate();
            return JSONObject.oK("新增成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }*/
    @Transactional
    @Override
    public JSONObject insertPro(Pro pro, Integer[] staIds, HttpServletRequest request) {
        String vcRemark = "";
        if(pro.getVcRemark() == null) {
            pro.setVcRemark(vcRemark);
        }
        try {
            //新增时不能有工序id
            if(pro.getlProId() != null) {
                throw new ParamsErrorException("新增工序，不能有工序id");
            }
            if(pro.getlDataState()==null){
                pro.setlDataState(1);
            }
            // 如果参数不合法，抛出参数异常
            checkParam(pro);

            // 调用存储过程
            int row = proMapper.insertSelective(pro);
            if(row == 0) {
                throw new ModifyFailedException("新增工序失败！");
            }
            List<Pro> pros = proMapper.listPros(pro);
            if(pros!=null && staIds!=null && staIds.length>0){
                int flag = proListMapper.insertProList(pros.get(0).getlProId(),staIds,1);
                if(flag == 0) {
                    throw new ModifyFailedException("新增工位失败！");
                }
            }
            return JSONObject.oK("新增成功！");
        } catch (GlobalException e) {  //这里只捕获自定义异常
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 工序查询
     *
     * @author xuz
     * @date 2018/11/23 1:55 PM
     * @param pro
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Override
    public JSONObject queryPro(Pro pro) {
        List<Pro> listPro = null;
        try {
            Integer pagesize = pro.getPagesize();
            Integer pageindex = pro.getPageindex();
            if(pagesize != null && pageindex != null) {
                pro.setIncept(pagesize*(pageindex - 1));
            }
            Integer lProId = pro.getlProId();
            if(lProId != null) {
                //如果有工序id,则查询单个工序信息
                listPro = proMapper.getPro(lProId);
            } else{
                //查询多个部门
                listPro = proMapper.listPros(pro);
            }
            if (listPro.isEmpty()) {
                return JSONObject.oK("没有工序相关数据", listPro, 0);
            }
            //查询分页总数
            int count = proMapper.countPro(pro);
            return JSONObject.oK("查询成功", listPro, count);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    /***
     * 工序状态修改
     *
     * @author xuz
     * @date 2018/11/23 1:55 PM
     * @param lProIds, lDataState
     * @return com.indusfo.spc.vo.JSONObject
     */
    @Transactional
    @Override
    public JSONObject deletePro(Long[] lProIds, Integer lDataState) {
        try {
            if(lDataState == null) {
                throw new ParamsErrorException("数据状态不能为空");
            }else if(lDataState != 1 && lDataState != 2 && lDataState != 3) {
                throw new ParamsErrorException("数据状态错误");
            }
            if (lProIds == null || lProIds.length==0) {
                throw new ParamsErrorException("请选择工序");
            }

            // 执行存储过程
            int row = proMapper.deltePro(lProIds, lDataState);
            int i = proListMapper.deleteProListByProIds(lProIds);
            String msg = "";
            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (lDataState) {
                    case 1:
                        throw new ModifyFailedException("启用失败");
                    case 2:
                        throw new ModifyFailedException("删除失败");
                    case 3:
                        throw new ModifyFailedException("停用失败");
                    default:
                }
            } else {
                switch (lDataState) {
                    case 1:
                        msg = "启用成功";break;
                    case 2:
                        msg = "删除成功";break;
                    case 3:
                        msg = "停用成功";break;
                    default:
                }
            }
            return JSONObject.oK(msg);
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }

    }


    /***
     * 工序查询  排除数组中的数据
     *
     */
    @Override
    public JSONObject queryProIds(Pro pro, Long[] proIds) {
        List<Pro> listPro = null;
        try {
            Integer pagesize = pro.getPagesize();
            Integer pageindex = pro.getPageindex();
            if(pagesize != null && pageindex != null) {
                pro.setIncept(pagesize*(pageindex - 1));
            }
            if(proIds==null){
            }
            else if(proIds.length==0){
                proIds=null;
            }
            listPro = proMapper.listProIds(pro,proIds);
            if (listPro.isEmpty()) {
                return JSONObject.oK("没有工序相关数据", listPro, 0);
            }
            //查询分页总数
            int count =proMapper.countProIds(pro,proIds);
            return JSONObject.oK("查询成功", listPro,count );
        } catch (GlobalException e) {
            logger.error(e.getMessage(), e);
            return JSONObject.build(403, e.getMessage());
        }
    }

    @Override
    public JSONObject checkStation(Long[] lProIds) {
        if(lProIds!=null && lProIds.length>0){
            for (int i = 0; i < lProIds.length; i++) {
                List<ProList> proLists = proListMapper.queryByProId(Integer.valueOf(lProIds[i].intValue()));
                if(proLists!=null && proLists.size()>0){
                    return JSONObject.build(403, "工序下存在工位",true);
                }
            }
        }

        return JSONObject.build(403, "工序下不存在工位",false);
    }

    @Override
    public String checkNoRepeat(Pro pro) {
        //工序名称
        String vcProName = pro.getVcProName();
        //工序类型名称
        String vcItemName = pro.getVcItemName();
        if(StringUtils.isBlank(vcProName) && StringUtils.isBlank(vcItemName) && StringUtils.isBlank(pro.getVcRemark())){
            return "该行数据为空(原因:清空行内容时未清空彻底/未输入)";
        }
        if(StringUtils.isBlank(vcProName)){
            return "工序名称为空";
        }
        if (pro.getVcProName().length() > 50) {
            return "工序名称超过规定长度50";
        }
        if (pro.getVcRemark()!=null && pro.getVcRemark().length() > 50) {
            return "说明超过规定长度50";
        }
        // 校验工序名不能重复
        Integer proCounts = proMapper.selectPros(pro);
        if (proCounts != 0) {
            return "该工序名已存在";
        }
        Map<String, Datadict> tdatadictMap = uploadMapper.queryType(101031);
        if(!tdatadictMap.containsKey(vcItemName)){
            return "工序类型填写不规范/错误";
        }
        Datadict tdatadict = tdatadictMap.get(vcItemName);
        pro.setProType(String.valueOf(tdatadict.getItemId()));
        return null;
    }

    @Override
    public JSONObject updateListPro(List<Pro> proList) {
        uploadMapper.updateListPro(proList);
        return null;
    }


    /**
     * 参数校验
     *
     * @author xuz
     * @date 2018/11/29 2:36 PM
     * @param pro, vcRemark]
     * @return void
     */
    private void checkParam(Pro pro) {
       /* if (pro.getLDepId() == null) {
            throw new ParamsErrorException("请选择部门");
        }*/
        if (StringUtils.isEmpty(pro.getVcProName())) {
            throw new ParamsErrorException("工序名不能为空");
        }
        if (pro.getVcProName().length() > 50) {
            throw new ParamsErrorException("工序名称超过规定长度50");
        }
        if (pro.getVcRemark().length() > 50) {
            throw new ParamsErrorException("说明超过规定长度50");
        }

        if(pro.getProType()==null || pro.getProType().length()==0){
            throw new ParamsErrorException("选择工序类型");
        }
        // 校验工序名不能重复
        Integer proCounts = proMapper.selectPros(pro);
        if (proCounts != 0) {
            throw new ParamsErrorException("该工序名已存在");
        }
    }
}
